package com.thumb.dao.Impl;

import com.thumb.bean.Thumb;
import com.thumb.dao.ThumbDao;
import com.thumb.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Spider Man
 * @Description:
 * @Date Created in 2020-09-08 12:39
 * @Modified By:
 */
public class ThumbDaoImpl implements ThumbDao {
    @Override
    public void updateNumber(int oldNum,int newNum) {
        Connection connection = DruidUtil.getConnection();
        String sql = "update thumb set number = ? where number = ?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,newNum);
            preparedStatement.setInt(2,oldNum);
            preparedStatement.execute();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public List<Thumb> findNumber() {
        List<Thumb> list = new ArrayList<>();
        Connection connection = DruidUtil.getConnection();
        String sql = "select * from thumb";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            assert connection != null;
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                Thumb thumb = new Thumb();
                thumb.setNumber(resultSet.getInt("number"));
                list.add(thumb);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            assert connection != null;
            assert preparedStatement != null;
            assert resultSet != null;
            DruidUtil.close(connection,preparedStatement,resultSet);
        }
        return list;
    }
}
